var express = require('express');
var router = express.Router();
var Floor = require("../models/floor");

var multer  = require('multer');
var upload = multer({ dest: 'upload/' });
var shangchuan = require('../models/uplodaTengxun_cos.js');


//获取广告数据
router.get('/getFloor', function(req, res, next) {
    var model = Floor.find();
    model.exec(function(err,result){
        if(err){
            res.json({
                status:"1",
                msg:err.message
            })
        }else{
            res.json({
                status:"0",
                msg:"",
                result:{
                    count:result.length,
                    list:result
                }
            })
        }
    });
});

//添加Floor
var cpUpload = upload.fields([{ name: 'mainIcon', maxCount: 1 }, { name: 'secondIcons', maxCount: 1 }]);
router.post('/addFloor', cpUpload, async function (req, res, next) {

    let param = {
        freeze:true,
        relationGoods : []
    };

    if(req.body.title != ''){
        param["title"] = req.body.title;
    }
    if(req.files['mainIcon'] != undefined){
        param["mainIcon"] = await shangchuan(req.files["mainIcon"][0]);
    }
    if(req.files['secondIcons'] != undefined){
        param["secondIcons"] = await shangchuan(req.files["secondIcons"][0]);
    }

    Floor.findOne({title:req.body.title},function(err,result) {
        if (err) {
            res.json({
                status: "1",
                msg: err.message,
                result: ""
            })
        } else {
             if(result == null){
                 Floor.create( param ,function(err,doc){
                     if(err){
                         res.json({
                             status:"1",
                             msg:err.message,
                             result: ""
                         })
                     }else{
                         if(doc){
                             res.json({
                                 status:"0",
                                 msg:"添加成功",
                                 result: "suc"
                             })
                         }
                     }
                 })
             }else{
                 res.json({
                     status:"1",
                     msg:"楼层名称已存在",
                     result: ""
                 })
             }
        }
    })


})

//查找一个Floor
router.get('/findFloor', function(req, res, next) {
    Floor.findOne({_id:req.param("id")},function(err,result) {
        if (err) {
            res.json({
                status: "1",
                msg: err.message,
                result: ""
            })
        } else {
            res.json({
                status:"0",
                msg:"",
                result:{
                    list:result
                }
            })
        }
    })
});

//删除Floor
router.post('/delFloor', function(req, res, next) {
    Floor.remove({_id:req.body.id}, function (err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err.message,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"删除成功",
                    result: "suc"
                })
            }
        }
    });
});

//冻结floor
router.post('/freezeFloor', function(req, res, next) {
    Floor.update({
        _id:req.body.id
    },{
        $set:{'freeze':req.body.freeze}
    },function(err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err.message,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"修改成功",
                    result: "suc"
                })
            }
        }
    });
});

//修改Floor
router.post('/editFloor', cpUpload ,async function(req, res, next) {

    let param = {};

    if(req.body.title != ''){
        param["title"] = req.body.title;
    }
    if(req.files['mainIcon'] != undefined){
        param["mainIcon"] = await shangchuan(req.files["mainIcon"][0]);
    }
    if(req.files['secondIcons'] != undefined){
        param["secondIcons"] = await shangchuan(req.files["secondIcons"][0]);
    }

    Floor.findOne({title:req.body.title},function(err,result) {
        if (err) {
            res.json({
                status: "1",
                msg: err.message,
                result: ""
            })
        } else {
            if(result == null || result._id == req.body.id){
                Floor.update({
                    _id:req.body.id
                },{
                    $set:param
                },function(err,doc){
                    if(err){
                        res.json({
                            status:"1",
                            msg:err.message,
                            result: ""
                        })
                    }else{
                        if(doc){
                            res.json({
                                status:"0",
                                msg:"修改成功",
                                result: "suc"
                            })
                        }
                    }
                });
            }else{
                res.json({
                    status:"1",
                    msg:"楼层名称已存在",
                    result: ""
                })
            }
        }
    })
});

var mongoose = require('mongoose');

//添加modular
router.post('/addModular', upload.array("url"), async function(req, res, next) {

    let param = {
        _id:mongoose.Types.ObjectId(),
    };

    if(req.files.length != 0){
        param["url"] = await shangchuan(req.files[0]);
    }
    if(req.body.title != ''){
        param["title"] = req.body.title;
    }
    if(req.body.price != ''){
        param["price"] = req.body.price;
    }
    if(req.body.goodsId != ''){
        param["goodsId"] = req.body.goodsId;
    }
    if(req.body.salse != ''){
        param["salse"] = req.body.salse;
    }

    Floor.find({_id:req.body.id},function(err,result) {
        if (err) {
            res.json({
                status: "1",
                msg: err.message,
                result: ""
            })
        } else {
            if (result.length > 6) {
                res.json({
                    status: "1",
                    msg: "商品关联最多6个",
                    result: ""
                })
            } else {
                let titlearry = [];
                result[0].relationGoods.forEach((item) => {
                    titlearry.push(item.title)
                });
                if (titlearry.indexOf(req.body.title) < 0) {
                    Floor.update({"_id": req.body.id}, {
                        $push: {
                            relationGoods: param
                        }
                    }, function (err1, result) {
                        if (err1) {
                            res.json({
                                status: "1",
                                msg: err1.message,
                                result: ""
                            })
                        } else {
                            res.json({
                                status: "0",
                                msg: "添加成功",
                                result: "suc"
                            })
                        }
                    });
                } else {
                    res.json({
                        status: "1",
                        msg: "商品关联名称重复",
                        result: ""
                    })
                }
            }
        }
    })
});

//查找一个Modular
router.get('/findModular', function(req, res, next) {

    Floor.find({_id:req.param("id")},function(err,result) {
        if (err) {
            res.json({
                status: "1",
                msg: err.message,
                result: ""
            })
        } else {
            result[0].relationGoods.forEach((item)=>{
                if(item._id == req.param("index")){
                     res.json({
                        status:"0",
                        msg:"",
                        result:{
                            list:item
                        }
                    })
                }
            });
        }
    })
});

router.post('/editModular', upload.array("url"),async function(req, res, next) {
    let url ="";
    if(req.files.length != 0){
        url = await shangchuan(req.files[0]);
    }

    Floor.findOne({_id:req.body.id},  function(err,result) {
        if (err) {
            res.json({
                status: "1",
                msg: err.message,
                result: ""
            })
        } else {
            let titlearry = [];
            let idarry = [];
            if(req.body.title != ''){
                result.relationGoods.forEach((item)=>{
                    titlearry.push(item.title);
                    idarry.push(item._id)
                });
            }
            if(titlearry.indexOf(req.body.title) < 0 || idarry[titlearry.indexOf(req.body.title)] == req.body.ind){
                result.relationGoods.forEach((item)=>{
                    if(item._id == req.body.ind){
                        console.log(url)
                        if(url != ''){
                            item.url = url;
                        }
                        if(req.body.title != ''){
                            item.title = req.body.title;
                        }
                        if(req.body.price != ''){
                            item.price = req.body.price;
                        }
                        if(req.body.goodsId != ''){
                            item.goodsId = req.body.goodsId;
                        }
                    }
                });

                result.save(function(err1,doc1){
                    if(err1){
                        res.json({
                            status:"1",
                            msg:err.message,
                            result: ""
                        })
                    }else{
                        res.json({
                            status:"0",
                            msg:"更新成功",
                            result: "suc"
                        })
                    }
                })
            }else{
                res.json({
                    status:"1",
                    msg:"商品关联名称重复",
                    result:""
                })
            }
        }
    })
});

//删除Modular
router.post('/delModular', function(req, res, next) {
    Floor.update({
        _id:req.body.id
    },{
        $pull:{
            "relationGoods":{
                "_id":req.body.index
            }
        }
    },function(err,doc){
        if(err){
            res.json({
                status:"1",
                msg:err.message,
                result: ""
            })
        }else{
            if(doc){
                res.json({
                    status:"0",
                    msg:"删除成功",
                    result: "suc"
                })
            }
        }
    });
});

module.exports = router;
